﻿using System;
using System.Collections.ObjectModel;
using System.Data;
using System.Linq;
using System.Windows.Forms;
using Sunlight.Dispatch.Dal;
using Sunlight.Dispatch.UI.Controls;
using Sunlight.Dispatch.UI.Extensions;
using Sunlight.Dispatch.Model;

namespace Sunlight.Dispatch.UI {
    public partial class SideListConfigFrm : BaseFrm {
        private readonly ObservableCollection<TSide> sides = new ObservableCollection<TSide>();
        public SideListConfigFrm() {
            InitializeComponent();
        }

        private void SideListConfigFrm_Load(object sender, EventArgs e) {
            dataGridView1.ReadOnly = false;
            dataGridView1.AutoGenerateColumns = true;
            dataGridView1.AllowUserToAddRows = true;
            dataGridView1.AllowUserToDeleteRows = true;
            dataGridView1.AutoGenerateColumns = false;
            this.dataGridView1.DataSource = null;
            this.dataGridView1.CellEndEdit += DataGridView1_CellEndEdit;
            this.dataGridView1.KeyDown += DataGridView1_KeyDown;
            this.OnControlCreated(this.dataGridView1, null);

            this.InitComboBoxForDataBase(this.comboBoxDataBase.ComboBox);
        }

        private void DataGridView1_KeyDown(object sender, KeyEventArgs e) {
            if(e.KeyCode == Keys.Enter) {
                tsbDelete_Click(null, null);
            }
        }

        private void DataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e) {
            var tside = this.dataGridView1.Rows[e.RowIndex].DataBoundItem as TSide;
            if(tside == null)
                return;
            tside.IsNeedSubmit = true;
        }

        private void tsbSave_Click(object sender, EventArgs e) {
            if(this.dataGridView1.IsCurrentCellDirty) {
                this.dataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit);
            }
            if(this.dataGridView1.Rows.Count <= 0) {
                MessageBoxEx.Show("没有需要保存的数据，请确认");
                return;
            }

            var items = this.dataGridView1.Rows.Cast<DataGridViewRow>().Select(d => d.DataBoundItem).Cast<TSide>().ToList();
            if(!items.Any(d => d.IsNeedSubmit)) {
                MessageBoxEx.Show("没有需要保存的数据，请确认");
                return;
            }
            if(this.comboBoxDataBase.ComboBox.SelectedItem == null) {
                MessageBoxEx.Show("请选择数据库，请确认");
                return;
            }
            var db = this.comboBoxDataBase.ComboBox.SelectedItem as ConnectStringConfigTb;
            if(db == null)
                return;
            using(var dataContext = new MonitorSettingDataContext(db.ConnectString)) {
                var ids = items.Select(d => d.ID).ToArray();
                if(ids.Any()) {
                    foreach(var currentData in dataContext.TSide.Where(d => ids.Contains(d.ID)).ToList()) {
                        var updated = items.FirstOrDefault(d => d.ID == currentData.ID);
                        if(updated != null) {
                            currentData.Name = updated.Name;
                            currentData.Code = updated.Code;
                        }
                    }
                }
                foreach(var item in items.Where(d => d.ID <= 0).ToList()) {
                    dataContext.TSide.InsertOnSubmit(item);
                }
                dataContext.SubmitChanges();
            }
        }

        private void tsbBtnSearch_Click(object sender, EventArgs e) {
            if(sides.Any(d => d.IsNeedSubmit)) {
                MessageBoxEx.Show("请先保存数据后，执行查询");
                return;
            }
            if(this.comboBoxDataBase.ComboBox.SelectedItem == null) {
                MessageBoxEx.Show("请选择数据库，请确认");
                return;
            }
            if(this.comboBoxDataBase.SelectedItem == null) {
                MessageBoxEx.Show("数据库选项不能为空，请选择数据库");
                return;
            }
            var db = this.comboBoxDataBase.ComboBox.SelectedItem as ConnectStringConfigTb;
            if(db == null)
                return;
            using(var dataContext = new MonitorSettingDataContext(db.ConnectString)) {
                this.IsLoading = true;
                IQueryable<TSide> sidesInternal = dataContext.TSide;
                if(!string.IsNullOrEmpty(this.tstbSearchText.Text)) {
                    var condition = this.tstbSearchText.Text.ToLower();
                    sidesInternal = sidesInternal.Where(d => d.Code.ToLower().Contains(condition) || d.Name.ToLower().Contains(condition));
                }

                var data = sidesInternal.ToList();
                data.ForEach(d => d.IsNeedSubmit = false);
                data.ForEach(d => sides.Add(d));
                data.ForEach(d => d.ConnectString = db.ConnectString);
                this.dataGridView1.DataSource = data;
                this.IsLoading = false;
            }
        }

        private void tsbInsert_Click(object sender, EventArgs e) {
            var frm = new TSideOperationFrm();
            frm.MdiParent = this.MdiParent;
            frm.EditSubmitted += Frm_EditSubmitted;
            frm.Show();
        }

        private void Frm_EditSubmitted(object sender, SubmittedEventArgs e) {
            var form = sender as Form;
            if(form == null)
                return;
            form.Close();
            this.tsbBtnSearch_Click(this.tsbBtnSearch, e);
        }

        private void tsbDelete_Click(object sender, EventArgs e) {
            if(dataGridView1.SelectedRows.Count <= 0)
                return;
            var items = this.dataGridView1.SelectedRows.Cast<DataGridViewRow>().Select(d => d.DataBoundItem).Cast<TSide>();
            var ids = items.Select(d => d.ID).ToArray();
            var okOrCancel = MessageBoxEx.Show(this, "删除配置同时会删除配置的调度地址清单,确定删除选择的数据吗?", "询问", MessageBoxButtons.OKCancel, MessageBoxIcon.Asterisk);
            if(okOrCancel == DialogResult.Cancel)
                return;
            using(var context = new MonitorSettingDataContext(items.First().ConnectString)) {
                var result = context.TSide.Where(d => ids.Contains(d.ID)).ToList();
                var details = context.TSideList.Where(d => ids.Contains(d.ParentID)).ToList();
                context.TSide.DeleteAllOnSubmit(result);
                context.TSideList.DeleteAllOnSubmit(details);
                context.SubmitChanges();

                //此处后面待优化
                this.tsbBtnSearch_Click(this.tsbBtnSearch, e);
            }
        }
    }
}
